import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  renameImages: (folderPath: string, startNumber: number) =>
    ipcRenderer.invoke('rename-images', { folderPath, startNumber }),
  showOpenDialog: (options: any) => ipcRenderer.invoke('show-open-dialog', options),
  modaoDomToForm: async (params: any, callback: (result: any) => void) => {
    const data = await ipcRenderer.invoke('modao-dom-to-form', params)
    callback(data)
  },
  websiteToPage: async (params: any, callback: (result: any) => void) => {
    const data = await ipcRenderer.invoke('website-to-page', params)
    callback(data)
  },
  dictToDb: async (params: any, callback: (result: any) => void) => {
    const data = await ipcRenderer.invoke('dict-to-db', params)
    callback(data)
  },
  domToForm: async (params: any, callback: (result: any) => void) => {
    const data = await ipcRenderer.invoke('dom-to-form', params)
    callback(data)
  },
  domToTable: async (params: any, callback: (result: any) => void) => {
    const data = await ipcRenderer.invoke('dom-to-table', params)
    callback(data)
  },
  domToTableDetail: async (params: any, callback: (result: any) => void) => {
    const data = await ipcRenderer.invoke('dom-to-table-detail', params)
    callback(data)
  },
  domToDict: async (params: any, callback: (result: any) => void) => {
    const data = await ipcRenderer.invoke('dom-to-dict', params)
    callback(data)
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
